package com.maoslv.security;

import com.alibaba.fastjson.JSON;
import com.maoslv.dto.AuthDto;
import com.maoslv.dto.Result;
import com.maoslv.pojo.User;
import com.maoslv.service.user.UserService;
import com.maoslv.utils.JWTUtil;
import com.maoslv.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登录成功
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtill;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //设置响应回去的类型
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        //生成jwt
        String token = JWTUtil.getToken(authentication.getName());
        User user = userService.getByUsername(authentication.getName());
        redisUtill.set(user.getUsername()+"-jwt",token);

        outputStream.write(JSON.toJSONString(Result.succ("登录成功",new AuthDto(user.getId(),user.getUsername(),token))).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
